package com.nanhang.controller;

import com.nanhang.entity.Student;
import com.nanhang.service.IStudentService;
import com.nanhang.util.PageResult;
import com.nanhang.util.R;
import com.nanhang.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jzy
 * @since 2025-01-07
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @GetMapping("/list")
    public R getStudent(){
        return R.ok().data("list",studentService.list());
    }

    @GetMapping("/findByPage/{page}/{pageSize}")
    public R findByPage(@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize){
        System.out.println("into serve");
        PageResult<Student> pr =studentService.findByPage(page,pageSize);
        System.out.println(pr);
        return R.ok().data("pr",pr);
    }

    @PostMapping("/search/{page}/{pageSize}")
    public R search(@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize,@RequestBody(required = false) StudentVO studentVO){
        System.out.println("controller");
        PageResult<Student> pr =studentService.search(page,pageSize,studentVO);
        return R.ok().data("pr",pr);
    }

    @PostMapping("/add")
    public R add(@RequestBody Student student){
        boolean save = studentService.save(student);
        if(save){
            return R.ok().message("添加成功");
        }else{
            return R.error().message("添加失败");
        }
    }

    @PostMapping("/update")
    public R update(@RequestBody Student student){
        boolean update = studentService.updateById(student);
        if(update){
            return R.ok().message("修改成功");
        }else{
            return R.error().message("修改失败");
        }
    }
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable("ids") String ids){
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        boolean delete = studentService.removeByIds(list);
        if(delete){
            return R.ok().message("删除成功");
        }else{
            return R.error().message("删除失败");
        }
    }
}
